package thread;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class MyThreadDemo16 {
    public static void main(String[] args) throws InterruptedException {

        //构造方法中写10 ，意思有10个线程
        CountDownLatch count = new CountDownLatch(10);//可以用这个 ，让一个线程执行多个任务

        //创建出10个线程负责下载任务
        for (int i = 0; i < 10; i++) {
            int id  = i;
            Thread t = new Thread(()-> {
                Random random = new Random();
                int time = random.nextInt(5) * 1000;
                System.out.println("线程" + id + "开始下载");
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程" + id + "下载结束");

                //告知CountDownLatch 我下载结束
                count.countDown();
            });

            t.start();
        }

        //通过await来等待所有线程结束
        count.await();
        System.out.println("所有线程结束");
    }
}
